package com.innovation.sys.common.shiro.realm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.innovation.sys.common.dto.RelationForAccountDTO;
import com.innovation.sys.pojo.SSysAccount;
import com.innovation.sys.service.AccountService;

public class UserRealm extends AuthorizingRealm {

	@Resource
	private AccountService accountService;

	private static Logger logger = LoggerFactory.getLogger(UserRealm.class);

	// 授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 获取用户凭证
		SSysAccount account = (SSysAccount) principals.getPrimaryPrincipal();
		logger.info("当前登录用户:{}" + account.toString());
		List<RelationForAccountDTO> selectByRelation = accountService.findUserPermission(account.getAccountId());
		Set<String> permissions = new HashSet<String>();
		Set<String> roles = new HashSet<String>();
		for (RelationForAccountDTO relationForAccountDTO : selectByRelation) {
			if (!(StringUtils.isEmpty(relationForAccountDTO.getrName())
					&& StringUtils.isEmpty(relationForAccountDTO.getPermission()))) {
				roles.add(relationForAccountDTO.getrName());
				permissions.add(relationForAccountDTO.getPermission());
			}
		}
		logger.info("角色:{}" + roles.toString() + "权限:{}" + permissions.toString());
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.setRoles(roles);
		simpleAuthorizationInfo.setStringPermissions(permissions);
		return simpleAuthorizationInfo;
	}

	// 认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken isToken = (UsernamePasswordToken) token;
		String password = String.valueOf(isToken.getPassword());
		SSysAccount account = accountService.findByName(isToken.getUsername());
		if (account == null) {
			throw new UnknownAccountException();
		}
		if (account.getStatus() == 0) {
			throw new LockedAccountException();
		}
		AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(account, password, getName());
		return authenticationInfo;
	}

}
